package com.fp.einvoice.utils;

import cn.hutool.core.io.FileUtil;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.opencv.core.Core;
import org.springframework.boot.system.ApplicationHome;

public final class OpenCV {

    private OpenCV(){
        throw new AssertionError();
    }

    /**
     * 初始化 OpenCV
     */
    public static void init() throws Exception{
        init("lib");
    }

    /**
     * 初始化 OpenCV
     * @param libDirPath opencv_java*.dll 或 opencv_java*.so 所在文件夹
     */
    public static void init(String libDirPath) throws Exception{
        initOpenCV(libDirPath);
    }

    /**
     * 初始化 OpenCV
     * @param libDirPath opencv_java*.dll 或 opencv_java*.so 所在文件夹
     */
    private static void initOpenCV(String libDirPath) throws Exception {
        String os = System.getProperty("os.name");
        File libOpencvFile = null;
        String filePath = "";
        if(os != null){
            os = os.toLowerCase();
            ApplicationHome ah = new ApplicationHome(OpenCV.class);
            File source = ah.getSource();
            filePath = source.getParentFile().getPath().replace("\\\\", "/");
            try {
                Logger.getLogger(OpenCV.class.getName()).log(Level.INFO, "os.name = " + os);
                if(os.contains("linux")) {
                    filePath = filePath + "/opencvlib/libopencv_java460.so";
                }else{
                    filePath = filePath + "/opencvlib/libopencv_java453.dll";
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(filePath != null && FileUtil.exist(filePath)){
            System.load(filePath);
        }else{
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        }
        Core.setErrorVerbosity(false);
        Logger.getLogger(OpenCV.class.getName()).log(Level.INFO, "Successfully loaded OpenCV native library.");
    }
}
